/*
 * Copyright 2017-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.openmessaging.storage.dledger.statemachine;

import io.openmessaging.storage.dledger.utils.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

public class RegisterSnapshotFile {

    private static final Logger logger = LoggerFactory.getLogger(RegisterSnapshotFile.class);

    private final String snapshotStorePath;

    public RegisterSnapshotFile(String snapshotStorePath) {
        this.snapshotStorePath = snapshotStorePath;
    }

    public boolean save(final Map<Integer, Integer> register) {
        try {
            IOUtils.object2File(snapshotStorePath, register);
        } catch (IOException e) {
            logger.error("Unable to save snapshot data", e);
            return false;
        }
        return true;
    }

    public Map<Integer, Integer> load() throws IOException, ClassNotFoundException {
        Object object = IOUtils.file2Object(this.snapshotStorePath);
        if (object instanceof Map) {
            Map<Integer, Integer> map = (Map<Integer, Integer>) object;
            return map;
        } else {
            throw new IOException("Unable to load data from file to map");
        }
    }
}
